#include"thread.h"


void* thread_run(void* argv)
{
    // (void*)argv;
    // // int pthread_detach(pthread_t thread);
    // cout<<"create thread success, the thread id is:" << pthread_self() <<endl;
    // pthread_exit((void*)2);  //no return 
    
    // //正常情况，线程return nullptr
    thread_top* td = static_cast<thread_top*>(argv);

    // size_t sum = 0;
    // for(int i = 0; i < td->_top;i++)
    // {
    //    sum += i;
    // }
    
    // td->_ret = (void*)sum;
    for(int i=0;i<td->_top;i++)
    {
        td->_ret += i; 
    }
    cout<<td->_name<<" "<<td->_ret<<endl;

    return td;
}

int main()
{
    //success :0
    //error   :error number

    /* int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                        void *(*start_routine) (void *), void *arg);arg是传入新线程执行方法的对应形参 */
    //创建10个新线程
    pthread_t tid[NUM];
    

    //创建累加对象
    for(int i =0;i<NUM;i++)
    {
        thread_top* t1 = new thread_top;
        t1->_top = 100+i;
        t1->_name = "thread_" + to_string(i); 
        int n = pthread_create(&tid[i],nullptr,thread_run,(void*)t1);
        if(n)
            perror("create: ");
        usleep(100000);
    }


    void* ret = nullptr;
    //等待线程退出
    for(int i = 0;i<NUM;i++)
    {
        int n = pthread_join(tid[i],&ret);
        if(n)   perror("join: ");
            
        // cout<<tid[i]<<" 的计算结果为: "<<ret<<endl;
    }

    //int pthread_cancel(pthread_t thread);
    

    sleep(1);//主进程退出，整个进程退出，新线程没有机会打印函数体的内容
    return 0;
}
